#include "logger_factory.hpp"
#include "logger_api.hpp"
#include "formatters/basic_formatter.hpp"
#include "formatters/json_formatter.hpp"
#include "core/logger_config.hpp"
#include "sinks/console_sink.hpp"
#include "sinks/file_sink.hpp"
#include "sinks/network_sink.hpp"
#include "sinks/filtering_sink.hpp"
#include "metrics/metrics_logger.hpp"
#include "metrics/metrics_sink.hpp"
#include <filesystem>
#include <iostream>

std::shared_ptr<ILogger> LoggerFactory::create(const LoggerConfig& config) {
    // 创建原始Logger (无Metrics方法)
    auto formatter = createFormatter(config.formatter);
    auto sinks = createSinks(config);

    auto raw_logger = std::make_shared<Logger>(
        formatter,
        sinks,
        config.async.main_queue_size,
        config.async.fallback_queue_size,
        config.async.flush_interval
    );

    // 若启用Metrics，则包装为MetricsLoggerDecorator
    std::shared_ptr<ILogger> logger = raw_logger;
    if (config.metrics.enabled) {
        logger = std::make_shared<MetricsLoggerDecorator>(logger, config.logger_name);

        // 同时为每个Sink添加MetricsSinkDecorator
        for (auto& sink : sinks) {
            sink = std::make_shared<MetricsSinkDecorator>(sink, sink->getName());
        }
    }

    logger->setLevel(config.level.default_level);

    if (config.backtrace.enabled) {
        logger->enableBacktrace(config.backtrace.size);
    }

    return logger;
}


std::shared_ptr<ILogger> LoggerFactory::createFromConfigFile(const std::string& config_file) {
    auto config = LoggerConfig::fromJsonFile(config_file);
    return create(config);
}


// 全局共享实例的实现
static std::shared_ptr<ILogger> g_shared_logger = nullptr;
static std::mutex g_shared_logger_mutex;

void LoggerFactory::initShared(const LoggerConfig& config) {
    std::lock_guard<std::mutex> lock(g_shared_logger_mutex);
    g_shared_logger = create(config);
}


void LoggerFactory::initSharedFromConfigFile(const std::string& config_file) {
    auto config = LoggerConfig::fromJsonFile(config_file);
    initShared(config);
}


std::shared_ptr<ILogger> LoggerFactory::getShared() {
    std::lock_guard<std::mutex> lock(g_shared_logger_mutex);
    if (!g_shared_logger) {
        // 如果从未初始化，则使用默认配置创建一个
        g_shared_logger = create(LoggerConfig{});
    }
    return g_shared_logger;
}


// 辅助方法 
std::shared_ptr<IFormatter> LoggerFactory::createFormatter(const FormatterConfig& config) {
    switch (config.type) {
        case FormatterConfig::Type::JSON:
            return std::make_shared<JsonFormatter>();
        case FormatterConfig::Type::Basic:
        default:
            return std::make_shared<BasicFormatter>();
    }
}

// createSinks 
std::vector<std::shared_ptr<ISink>> LoggerFactory::createSinks(const LoggerConfig& config) {
    std::vector<std::shared_ptr<ISink>> sinks;

    if (config.console.enabled) {
        auto console_sink = std::make_shared<ConsoleSink>(config.console.logger_name);
        if (config.filter.enabled && config.console.apply_filtering) {
            auto filtered_sink = std::make_shared<FilteringSink>(console_sink);

            // 添加过滤规则
            for (const auto& [pattern, replacement] : config.filter.filters) {
                filtered_sink->addFilter(pattern, replacement);
            }

            sinks.push_back(filtered_sink);
        }
        else {
            sinks.push_back(console_sink);
        }
    }
    // ---  创建文件 Sink ---
    if (config.file.enabled) {
        // 确保日志目录存在，这是一个很好的实践
        try {
            std::filesystem::path log_path(config.file.filename);
            if (log_path.has_parent_path()) {
                std::filesystem::create_directories(log_path.parent_path());
            }
        } catch (const std::exception& e) {
            std::cerr << "Error creating log directory for " << config.file.filename << ": " << e.what() << std::endl;
        }

        auto file_sink = std::make_shared<FileSink>(
            config.file.filename,
            config.file.max_size,
            config.file.max_files,
            config.file.logger_name
        );
        sinks.push_back(file_sink);
    }

    // ---  创建网络 Sink ---
    if (config.network.enabled) {
        if (config.network.url.empty()) {
            std::cerr << "Warning: Network sink is enabled but URL is empty. Sink not created." << std::endl;
        } else {
            // TODO: 在 V2.0 中，NetworkSink 的构造函数应该接收完整的配置，如超时
            // auto network_sink = std::make_shared<NetworkSink>(config.network);
            auto network_sink = std::make_shared<NetworkSink>(
                config.network.url,
                config.network.thread_pool_size,
                config.network.timeout,
                config.network.connect_timeout
            );
            sinks.push_back(network_sink);
        }
    }
    // ... etc for other sinks 以后有了在这里加

    if (sinks.empty()) {
        std::cerr << "Warning: No sinks were configured. Logs will be discarded." << std::endl;
    }
    return sinks;
}




